package org.example.admin.airway;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class addAirwayView extends JFrame {
    private JTextField airwayIdField,departureField,arrivalField;
    private JButton addButton;

    public addAirwayView() {
        setTitle("管理端航线信息添加页面");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(8, 2));

        JLabel airwayIdLabel = new JLabel("航线id");
        airwayIdField = new JTextField();
        JLabel departureLabel = new JLabel("出发点");
        departureField = new JTextField();
        JLabel arrivalLabel = new JLabel("目的地");
        arrivalField = new JTextField();
        addButton = new JButton("添加");

        // 添加组件到窗口
        add(airwayIdLabel);
        add(airwayIdField);
        add(departureLabel);
        add(departureField);
        add(arrivalLabel);
        add(arrivalField);
        add(new JLabel()); // 占位
        add(addButton);

        // 添加添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUserInfoToDatabase();
            }
        });
    }

    private void addUserInfoToDatabase() {
        String airwayId = airwayIdField.getText();
        String departure = departureField.getText();
        String arrival = arrivalField.getText();

        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlines", "root", "123456");

            // 创建插入语句
            String insertQuery = "INSERT INTO air_airway (airway_id, departure, arrival) VALUES (?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(insertQuery);
            statement.setString(1,airwayId);
            statement.setString(2, departure);
            statement.setString(3, arrival);

            // 执行插入操作
            statement.executeUpdate();

            // 关闭连接和语句
            statement.close();
            conn.close();

            // 提示添加成功
            JOptionPane.showMessageDialog(this, "添加成功");

            // 清空输入框
            clearFields();

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage());
        }
    }

    private void clearFields() {
        airwayIdField.setText("");
        departureField.setText("");
        arrivalField.setText("");
    }

    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            addAirwayView addAirwayForm = new addAirwayView();
//            addAirwayForm.setSize(300, 200);
//            addAirwayForm.setVisible(true);
//        });
    }
}